package com.sinoglobal.wallet.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.TextUtil;


/**
 * @author ty
 * @createdate 2012-9-19 上午10:40:06
 * @Description: Http请求
 */
public class ConnectionUtil {

	private static final String ACCEPT = "Accept-Charset";
	private static final String UTF8 = "UTF-8";
	private static final String UTF8_ES = "UTF-8,*";
	private static final String CONNECTION_JSON = "json";
	private static final String APP_JSON = "APPLICATION/JSON";
	private static final String REQUEST_URL = "请求：URL:-->:";
	private static final String RESPONSE_STATUS = "响应状态码：";
	private static final String RESPONSE_PARAMS = "---返回的参数为--->>：";
	private static final String TERMINAL_ID = "terminalId";

	private static Date serverDate; // 服务器时间

	public static Date getServerDate() {
		return serverDate;
	}

	private static String execute(HttpUriRequest req) throws Exception {
		long startTime = System.currentTimeMillis();

		String result = null;
		InputStream instream = null;
		try {
			HttpResponse response = executeLoad(req);
			if (response != null) {
				int statusCode = response.getStatusLine().getStatusCode();
				LogUtils.d(RESPONSE_STATUS + statusCode);
				switch (statusCode) {
				case HttpStatus.SC_OK:
					// result = parseResponse(response, instream);
					result = EntityUtils.toString(response.getEntity(), UTF8);
					// result = EntityUtils.toString(response.getEntity(),
					// UTF8);GBK
					break;
				case HttpStatus.SC_FORBIDDEN: // 验证未通过
					break;
				case HttpStatus.SC_NOT_FOUND: // 请求错误
					break;
				}
			}
		} finally {
		}

		// 打包时应该注释
		long endTime = System.currentTimeMillis();
		String info = "请求：Time:" + (endTime - startTime) + "-->:"
				+ req.getURI();
		LogUtils.d(info);
		if (TextUtil.stringIsNull(result)) {
			throw new Exception("request not data :" + req.getURI());
		}
		LogUtils.d(RESPONSE_PARAMS + result);
		return result;
	}

	/**
	 * @author ty
	 * @createdate 2012-11-3 下午9:46:54
	 * @Description: 加载数据
	 * @param req
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws Exception
	 */
	public static HttpResponse executeLoad(HttpUriRequest req) throws ClientProtocolException, IOException  {
		HttpClient httpclient = W_CustomerHttpClient.getInstance();
		req.addHeader(ACCEPT, UTF8_ES);
		HttpResponse response = httpclient.execute(req);
		return response;
	}

	/**
	 * 
	 * @author ty
	 * @createdate 2013-3-21 上午10:22:01
	 * @Description: post请求
	 * @param params
	 *            请求的参数封装
	 * @return
	 * @throws Exception
	 * 
	 */
//	public static String post(Map<String, Object> params, String name)
//			throws Exception {
//		String URLNew = URL1 + name;
//		HttpPost httpost = new HttpPost(URLNew);
//		String json = JSON.toJSONString(params);
//		json = new String(Base64Utils.encode(json.getBytes()));
//		LogUtils.i("请求的url为==" + URLNew);
//		LogUtils.i("SUBMIT" + json);
//		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//		nvps.add(new BasicNameValuePair("json", json == null ? null : json));
//		if (params != null) {
//			for (String key : params.keySet()) {
//				LogUtils.i("key:" + key + ", value:" + params.get(key));
//			}
//			params.clear();
//			params = null;
//		}
//		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//		return execute(httpost);
//	}
	public static String postNew(Map<String, Object> params, String name,int urlFlag)
			throws Exception {
		String URLNew = getCommentUrl(urlFlag)+name; 
		HttpPost httpost = new HttpPost(URLNew);
		String json = JSON.toJSONString(params);
		LogUtils.i("请求的url为==" + URLNew);
		LogUtils.i("SUBMIT" + json);
		httpost.setEntity(new StringEntity(json, HTTP.UTF_8));
		return execute(httpost);
	}
	public static String getCommentUrl(int whichUrl) {
		switch (whichUrl) {
		case SinoConstans.SERVER_FLAG:
			return SinoConstans.SERVER_URL;
		case SinoConstans.SERVER_Encryption_FLAG:
			return SinoConstans.SERVER_Encryption_URL;
		case SinoConstans.SERVER_Coupon_FLAG:
			return SinoConstans.SERVER_Coupon_URL;
		default:
			return SinoConstans.SERVER_URL;
		}
	}
	// 用于测试 第一个参数是map参数，第二个参数是接口全路径。第三个参数是空字符串
//	public static String post(Map<String, Object> params, String url,
//			String empty) throws Exception {
//		String URLNew = url; 
//		HttpPost httpost = new HttpPost(URLNew);
//		String json = JSON.toJSONString(params);
//		LogUtils.i("请求的url为==" + URLNew);
//		LogUtils.i("SUBMIT" + json);
//		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//		nvps.add(new BasicNameValuePair("json", json == null ? null : json));
//		if (params != null) {
//			for (String key : params.keySet()) {
//				LogUtils.i("key:" + key + ", value:" + params.get(key));
//			}
//			params.clear();
//			params = null;
//		}
//		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//		return execute(httpost);
//	}
	
	public static String post(Map<String, Object> params, String url,
			String empty) throws Exception {
		String URLNew = url; 
		HttpPost httpost = new HttpPost(URLNew);
		String json = JSON.toJSONString(params);
		LogUtils.i("请求的url为==" + URLNew);
		LogUtils.i("SUBMIT" + json);
		httpost.setEntity(new StringEntity(json, HTTP.UTF_8));
		return execute(httpost);
	}
}
